#include "tank.h"
#include "rm67162.h"

// ====================================================================================
// Tank 坦克遥控类实现
// ====================================================================================

Tank::Tank(Screen& screen, Keys& keys, NRF& nrf)
  : _screen(screen), _keys(keys), _nrf(nrf) {
}

void Tank::main() {
  TankKVS tank_kvs;

  // 初始化NRF通信
  initNRF();

  // 初始化屏幕
  _screen.spr.fillSprite(TFT_BLACK);
  _screen.spr.setTextDatum(TL_DATUM);  // 字体对齐方式 TL_DATUM:左上对齐(基准坐标为左上角)

  while (true) {
    // 更新按键状态
    _keys.kvs_update();

    // 更新控制数据
    updateControlData(tank_kvs);

    // 发送控制数据
    sendControlData(tank_kvs);

    // 显示控制数据
    displayControlData(tank_kvs);

    // 检测退出按键
    if (_keys.x.pressed()) {
      _screen.clearAndCenter();
      break;
    }

    delay(20);
  }
}

void Tank::initNRF() {
  const byte address[6] = ADDRESS_0;

  _nrf.radio.openWritingPipe(address);  // 发送端打开通信通道
  _nrf.radio.setPALevel(NRF_LEVEL);     // 设置通信功率
  _nrf.radio.stopListening();           // 停止监听，即设置为发送端
}

void Tank::updateControlData(TankKVS& kvs) {
  kvs.L_up = _keys.kvs.L_up;
  kvs.L_down = _keys.kvs.L_down;
  kvs.R_up = _keys.kvs.R_up;
  kvs.R_down = _keys.kvs.R_down;
  kvs.LX = _keys.kvs.LX;
  kvs.LY = _keys.kvs.LY;
  kvs.RX = _keys.kvs.RX;
  kvs.RY = _keys.kvs.RY;
  kvs.light = _keys.kvs.switch_L1;
  kvs.power = _keys.kvs.switch_R2;
  kvs.trigger = _keys.kvs.R_up;
}

void Tank::sendControlData(const TankKVS& kvs) {
  _nrf.radio.write(&kvs, sizeof(kvs));
}

void Tank::displayControlData(const TankKVS& kvs) {
  _screen.spr.fillSprite(TFT_BLACK);
  _screen.spr.drawString("LX: " + String(kvs.LX), 30, 20);
  _screen.spr.drawString("LY: " + String(kvs.LY), 30, 60);
  _screen.spr.drawString("RX: " + String(kvs.RX), 30, 100);
  _screen.spr.drawString("RY: " + String(kvs.RY), 30, 140);
  _screen.spr.drawString("light: " + String(kvs.light), 30, 180);
  _screen.spr.drawString("power: " + String(kvs.power), 30, 220);
  _screen.spr.drawString("trigger: " + String(!kvs.trigger), 30, 260);
  _screen.spr.drawString("OUT: X Key", 30, 400);

  lcd_PushColors(0, 0, _screen.spr.width(), _screen.spr.height(),
                 (uint16_t*)_screen.spr.getPointer());  // 将数据显示到屏幕上
}
